package com.roin.learn.activiti.service.impl;

import com.roin.learn.activiti.base.BaseServiceImpl;
import com.roin.learn.activiti.exception.BusinessException;
import com.roin.learn.activiti.service.ProcessFormService;
import com.roin.learn.activiti.service.ProcessService;
import com.roin.learn.activiti.utils.ProcessFormUtil;
import org.activiti.engine.FormService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.StartFormData;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 流程表单业务实现类
 */
@Service
public class ProcessFormServiceImpl extends BaseServiceImpl implements ProcessFormService{
    @Resource
    FormService formService;
    @Resource
    RepositoryService repositoryService;
    @Resource
    ProcessService processService;


    public String getStartFromHtml(String processDefintionId){
        ProcessDefinition processDefintion = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefintionId).singleResult();
        if (processDefintion==null)
            throw  new BusinessException(String.format("ID为%s的流程定义不存在！",processDefintionId));
        if (processDefintion.hasStartFormKey()){//外置表单
            Object object = formService.getRenderedStartForm(processDefintionId);
            return object.toString();//整个页面，参数已经赋值
        }else{//内置表单
            List<FormProperty> properties = getStartFormProperties(processDefintionId);
            return ProcessFormUtil.toHtml(properties);
        }
    }
    public String getTaskFormHtml(String taskId){
        Task task = processService.queryTaskById(taskId);
        if (task==null)
            throw  new BusinessException(String.format("ID为%s的流程任务不存在！",taskId));
        if (StringUtils.isNotEmpty(task.getFormKey())){//外置表单
            Object object = formService.getRenderedTaskForm(task.getId());
            return object.toString();//整个页面，参数已经赋值
        }else{//内置表单
            List<FormProperty> properties = getTaskFormProperties(taskId);
            return ProcessFormUtil.toHtml(properties);
        }
    }
    @Override
    public List<FormProperty> getStartFormProperties(String processDefintionId) {
        StartFormData startFormData = formService.getStartFormData(processDefintionId);
        if (startFormData==null)
            return null;
        return startFormData.getFormProperties();
    }

    @Override
    public List<FormProperty> getTaskFormProperties(String taskId) {
        TaskFormData taskFormData = formService.getTaskFormData(taskId);
        if (taskFormData==null)
            return null;
        return taskFormData.getFormProperties();
    }
}
